/**
 * 抽屉管理器类
 * 用于管理主机连接、常用目录和备忘录功能
 */
class DrawerManager {
    constructor() {
        this.layer = null;
        this.form = null;
        this.$ = null;
        this.drawerIndex = null; // 存储抽屉的layer索引
        this.eventsInitialized = false; // 标记事件是否已初始化
        
        // 数据存储
        this.hosts = JSON.parse(localStorage.getItem('hosts') || '[]');
        this.directories = JSON.parse(localStorage.getItem('directories') || '[]');
        this.currentHost = localStorage.getItem('currentHost') || '未连接';
        this.memo = localStorage.getItem('memo') || '';
        
        this.init();
    }

    /**
     * 初始化
     */
    init() {
        const self = this;
        layui.use(['layer', 'form'], function(){
            self.layer = layui.layer;
            self.form = layui.form;
            self.$ = layui.$;
            self.initDefaultData();
            self.bindTriggerEvent();
        });
    }

    /**
     * 初始化默认数据
     */
    initDefaultData() {
        if (this.hosts.length === 0) {
            this.hosts = [
                {
                    name: '开发服务器',
                    ip: '192.168.1.100',
                    port: '22',
                    username: 'developer',
                    password: '******',
                    path: '/var/www'
                },
                {
                    name: '生产服务器',
                    ip: '10.0.0.50',
                    port: '2222',
                    username: 'admin',
                    password: '******',
                    path: '/home/admin'
                }
            ];
        }

        if (this.directories.length === 0) {
            this.directories = [
                {alias: '项目根目录', path: '/var/www/project'},
                {alias: '日志目录', path: '/var/log/nginx'},
                {alias: '配置目录', path: '/etc/nginx'}
            ];
        }

        if (!this.memo) {
            this.memo = '这里可以记录一些临时内容...\n\n例如：\n- 待处理的任务\n- 重要的命令\n- 临时笔记';
        }

        this.saveData();
    }

    /**
     * 绑定触发按钮事件
     */
    bindTriggerEvent() {
        const self = this;
        document.getElementById('openDrawer').onclick = function() {
            self.openDrawer();
        };
    }

    /**
     * 保存数据到本地存储
     */
    saveData() {
        localStorage.setItem('hosts', JSON.stringify(this.hosts));
        localStorage.setItem('directories', JSON.stringify(this.directories));
        localStorage.setItem('currentHost', this.currentHost);
        localStorage.setItem('memo', this.memo);
    }

    /**
     * 获取抽屉HTML内容
     */
    getDrawerContent() {
        return `
        <div class="drawer-content">
            <!-- 主机管理 -->
            <div class="section-card">
                <div class="section-title">
                    <i class="layui-icon layui-icon-service"></i> 主机管理
                </div>
                <div class="current-host">
                    <strong>当前主机：</strong><span id="currentHostName">${this.currentHost}</span>
                </div>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="addHost">
                    <i class="layui-icon layui-icon-add-1"></i> 添加主机
                </button>
                <div id="hostList"></div>
            </div>

            <!-- 常用目录 -->
            <div class="section-card">
                <div class="section-title">
                    <i class="layui-icon layui-icon-file"></i> 常用目录
                </div>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="addDir">
                    <i class="layui-icon layui-icon-add-1"></i> 添加目录
                </button>
                <div id="dirList"></div>
            </div>

            <!-- 备忘录 -->
            <div class="section-card">
                <div class="section-title">
                    <i class="layui-icon layui-icon-note"></i> 备忘录
                </div>
                <textarea class="layui-textarea memo-textarea" id="memoText" placeholder="在此记录临时内容...">${this.memo}</textarea>
                <button type="button" class="layui-btn layui-btn-sm" id="saveMemo" style="margin-top: 10px;">
                    <i class="layui-icon layui-icon-ok"></i> 保存备忘
                </button>
            </div>
        </div>
        `;
    }

    /**
     * 打开抽屉
     */
    openDrawer() {
        const self = this;
        this.drawerIndex = this.layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            area: ['800px', '100%'],
            shade: 0.3,
            shadeClose: true,
            offset: 'r',
            anim: 'slideLeft',
            content: this.getDrawerContent(),
            success: function(layero, index) {
                self.initDrawerContent();
                self.form.render();
            }
        });
    }

    /**
     * 初始化抽屉内容
     */
    initDrawerContent() {
        this.renderHostList();
        this.renderDirList();
        // 只在第一次初始化事件，避免重复绑定
        if (!this.eventsInitialized) {
            this.bindDrawerEvents();
            this.eventsInitialized = true;
        }
    }

    /**
     * 渲染主机列表
     */
    renderHostList() {
        let html = '';
        this.hosts.forEach((host, index) => {
            html += `
            <div class="host-item" data-index="${index}">
                <div style="margin-bottom: 8px;">
                    <strong>${host.name}</strong>
                    <span class="item-actions">
                        <button class="layui-btn layui-btn-xs layui-btn-normal apply-host">应用</button>
                        <button class="layui-btn layui-btn-xs test-host">测试</button>
                        <button class="layui-btn layui-btn-xs edit-host">编辑</button>
                        <button class="layui-btn layui-btn-xs layui-btn-danger delete-host">删除</button>
                    </span>
                </div>
                <div class="host-info">
                    <div>IP: ${host.ip}</div>
                    <div>端口: ${host.port}</div>
                    <div>用户: ${host.username}</div>
                    <div>路径: ${host.path}</div>
                </div>
            </div>
            `;
        });
        this.$('#hostList').html(html);
    }

    /**
     * 渲染目录列表
     */
    renderDirList() {
        let html = '';
        this.directories.forEach((dir, index) => {
            html += `
            <div class="dir-item" data-index="${index}">
                <div>
                    <strong>${dir.alias}</strong>
                    <span class="item-actions">
                        <button class="layui-btn layui-btn-xs layui-btn-normal jump-dir">跳转</button>
                        <button class="layui-btn layui-btn-xs edit-dir">编辑</button>
                        <button class="layui-btn layui-btn-xs layui-btn-danger delete-dir">删除</button>
                    </span>
                </div>
                <div style="font-size: 12px; color: #666; margin-top: 5px;">${dir.path}</div>
            </div>
            `;
        });
        this.$('#dirList').html(html);
    }

    /**
     * 绑定抽屉内事件（使用事件委托，避免重复绑定）
     */
    bindDrawerEvents() {
        const self = this;
        const $ = this.$;

        // 主机管理事件
        $(document).on('click', '#addHost', () => this.showHostForm());
        $(document).on('click', '.edit-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.showHostForm(self.hosts[index], index);
        });
        $(document).on('click', '.delete-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.deleteHost(index);
        });
        $(document).on('click', '.apply-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.applyHost(index);
        });
        $(document).on('click', '.test-host', function() {
            const index = $(this).closest('.host-item').data('index');
            self.testConnection(index);
        });

        // 目录管理事件
        $(document).on('click', '#addDir', () => this.showDirForm());
        $(document).on('click', '.edit-dir', function() {
            const index = $(this).closest('.dir-item').data('index');
            self.showDirForm(self.directories[index], index);
        });
        $(document).on('click', '.delete-dir', function() {
            const index = $(this).closest('.dir-item').data('index');
            self.deleteDirectory(index);
        });
        $(document).on('click', '.jump-dir', function() {
            const index = $(this).closest('.dir-item').data('index');
            self.jumpToDirectory(index);
        });

        // 备忘录事件
        $(document).on('click', '#saveMemo', () => this.saveMemo());
        $(document).on('input', '#memoText', function() {
            self.memo = $(this).val();
            self.saveData();
        });
    }

    /**
     * 显示主机表单
     */
    showHostForm(host, index) {
        const title = host ? '编辑主机' : '添加主机';
        const formData = host || {name: '', ip: '', port: '22', username: '', password: '', path: '/'};
        const self = this;
        
        const formIndex = this.layer.open({
            type: 1,
            title: title,
            area: ['450px', 'auto'],
            content: `
            <form class="layui-form" style="padding: 20px;">
                <div class="form-row">
                    <label>主机名：</label>
                    <input type="text" name="name" value="${formData.name}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>IP地址：</label>
                    <input type="text" name="ip" value="${formData.ip}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>端口：</label>
                    <input type="text" name="port" value="${formData.port}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>用户名：</label>
                    <input type="text" name="username" value="${formData.username}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>密码：</label>
                    <input type="password" name="password" value="${formData.password}" class="layui-input" required lay-verify="required">
                </div>
                <div class="form-row">
                    <label>初始路径：</label>
                    <input type="text" name="path" value="${formData.path}" class="layui-input" required lay-verify="required">
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="hostForm">确定</button>
                    <button type="button" class="layui-btn layui-btn-primary cancel-btn">取消</button>
                </div>
            </form>
            `,
            success: function(layero, currentIndex) {
                // 绑定取消按钮事件
                layero.find('.cancel-btn').on('click', function() {
                    self.layer.close(currentIndex);
                });

                self.form.on('submit(hostForm)', function(data) {
                    const hostData = data.field;
                    if (typeof index !== 'undefined') {
                        self.hosts[index] = hostData;
                    } else {
                        self.hosts.push(hostData);
                    }
                    self.saveData();
                    self.renderHostList();
                    self.layer.close(currentIndex);
                    self.layer.msg(title + '成功', {icon: 1});
                    return false;
                });
            }
        });
    }

    /**
     * 显示目录表单
     */
    showDirForm(dir, index) {
        const title = dir ? '编辑目录' : '添加目录';
        const formData = dir || {alias: '', path: ''};
        const self = this;
        
        const formIndex = this.layer.open({
            type: 1,
            title: title,
            area: ['400px', 'auto'],
            content: `
            <form class="layui-form" style="padding: 20px;">
                <div class="form-row">
                    <label>别称：</label>
                    <input type="text" name="alias" value="${formData.alias}" class="layui-input" required lay-verify="required" placeholder="给目录起个好记的名字">
                </div>
                <div class="form-row">
                    <label>路径：</label>
                    <input type="text" name="path" value="${formData.path}" class="layui-input" required lay-verify="required" placeholder="/home/user/documents">
                </div>
                <div style="text-align: center; margin-top: 20px;">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="dirForm">确定</button>
                    <button type="button" class="layui-btn layui-btn-primary cancel-btn">取消</button>
                </div>
            </form>
            `,
            success: function(layero, currentIndex) {
                // 绑定取消按钮事件
                layero.find('.cancel-btn').on('click', function() {
                    self.layer.close(currentIndex);
                });

                self.form.on('submit(dirForm)', function(data) {
                    const dirData = data.field;
                    if (typeof index !== 'undefined') {
                        self.directories[index] = dirData;
                    } else {
                        self.directories.push(dirData);
                    }
                    self.saveData();
                    self.renderDirList();
                    self.layer.close(currentIndex);
                    self.layer.msg(title + '成功', {icon: 1});
                    return false;
                });
            }
        });
    }

    /**
     * 删除主机
     */
    deleteHost(index) {
        const self = this;
        this.layer.confirm('确定删除此主机配置？', function(confirmIndex) {
            self.hosts.splice(index, 1);
            self.saveData();
            self.renderHostList();
            self.layer.close(confirmIndex);
        });
    }

    /**
     * 应用主机
     */
    applyHost(index) {
        this.currentHost = this.hosts[index].name;
        this.$('#currentHostName').text(this.currentHost);
        this.saveData();
        this.layer.msg('已应用主机：' + this.currentHost);
    }

    /**
     * 测试连接
     */
    testConnection(index) {
        const host = this.hosts[index];
        this.layer.msg('正在测试连接...', {icon: 16, time: 1000});
        setTimeout(() => {
            // 模拟测试连接
            const success = Math.random() > 0.3; // 70% 成功率
            if (success) {
                this.layer.msg('连接测试成功！', {icon: 1});
            } else {
                this.layer.msg('连接测试失败！', {icon: 2});
            }
        }, 1000);
    }

    /**
     * 删除目录
     */
    deleteDirectory(index) {
        const self = this;
        this.layer.confirm('确定删除此目录？', function(confirmIndex) {
            self.directories.splice(index, 1);
            self.saveData();
            self.renderDirList();
            self.layer.close(confirmIndex);
        });
    }

    /**
     * 跳转目录
     */
    jumpToDirectory(index) {
        const dir = this.directories[index];
        this.layer.msg('跳转到：' + dir.path, {icon: 1});
        // 这里可以添加实际的跳转逻辑
    }

    /**
     * 保存备忘录
     */
    saveMemo() {
        this.memo = this.$('#memoText').val();
        this.saveData();
        this.layer.msg('备忘录已保存', {icon: 1});
    }
}